package com.example.blog_system_ssm.service;

import com.example.blog_system_ssm.common.Constant;
import com.example.blog_system_ssm.common.SnowFlakeUtils;
import com.example.blog_system_ssm.component.RedisUtil;
import com.example.blog_system_ssm.mapper.UserMapper;
import com.example.blog_system_ssm.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;

    //初始化一个雪花算法工具类，设置机房ID和机器ID都为0
    SnowFlakeUtils snowFlakeUtils=new SnowFlakeUtils(0,0);

    public int add(String username,String password){
        //判断是否存在重复用户名
        if(userMapper.distinct(username)!=null){
            return -1;
        }
        return userMapper.add(snowFlakeUtils.nextId(), username,password);
    }

    public UserInfo login(String username,String password){
        return userMapper.login(username,password);
    }

    public UserInfo myInfoByUid(Long uid){
        return redisUtil.queryWithPassThrough(Constant.CACHE_USERINFO_KEY,uid,UserInfo.class,userMapper::myInfoByUid,
                Constant.CACHE_USERINFO_TTL, TimeUnit.MINUTES);
    }

    public UserInfo getUserByName(String username) {
        return userMapper.getUserByName(username);
    }
}
